package com.hmall.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.hmall.common.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取 "user-info" 字段的值（即用户 ID 字符串）；
        //若该值不为空，通过UserContext.setUser(Long.valueOf(userInfo))将用户 ID 转换为 Long 类型后存入UserContext类的 ThreadLocal 中。
        String userInfo = request.getHeader("user-info");
        if (ObjectUtil.isNotEmpty(userInfo)){
            UserContext.setUser(Long.valueOf(userInfo));

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //调用UserContext.removeUser()清除 ThreadLocal 中存储的用户 ID，避免线程复用导致的信息泄露。
        UserContext.removeUser();
    }
    //获取请求头中user-info用户ID，将它放到ThreadLocal






}
